<?php
/**
 * Notes:
 * User: LiaoHong
 * Date: 2025/10/25
 * Time: 9:03
 **/


namespace App\Services\Archives;

use App\Models\Archives\ArchivesAdmin;
use App\Models\Archives\ArchivesFile;
use App\Models\Archives\Borrow;
use App\Models\Project\Folder;
use App\Models\Project\Project;
use \Exception;
use Illuminate\Support\Facades\DB;

class ArchivesAdminService
{
    /**
     * @Notes:获取项目列表
     * @author: Liao Hong
     * @Time: 2025/10/25   11:09
     * @Interface getProjectList
     */
    public function getProjectList()
    {
        $row = Project::query()->get();
        $row = !empty($row) ? $row->toArray() : [];
        return $row;
    }
    /**
     * @Notes:获取档案目录结构树
     * @param $params
     * @author: Liao Hong
     * @Time: 2025/10/25   9:06
     * @Interface getFolederList
     */
    public function getFolederList($params)
    {
        if(!isset($params['project_id']) || empty($params['project_id'])){
            throw new Exception('请传入项目id，项目id不能为空！');
        }
        $type = DB::table('pull_setting')->where('id',1)->value('type');
        $rows = Folder::query()->where(['type'=>$type,'project_id'=>$params['project_id']])->get();
        $rows = !empty($rows) ? $rows->toArray() :[];
        $data = $this->buildFileTree($rows);
        return $data;
    }

    /**
     * @Notes:获取文件目录结构树
     * @param array $flatData
     * @return array
     * @author: Liao Hong
     * @Time: 2025/10/25   10:15
     * @Interface buildFileTree
     */
    function buildFileTree(array $flatData): array
    {
        // 1. 初始化两个数组：索引数组（id => 完整数据）、树形结果数组
        $idIndex = []; // 用于快速通过id查找对应数据，避免多次循环遍历
        $treeResult = [];
        // 2. 第一步循环：构建ID索引，并初始化每个节点的children数组
        foreach ($flatData as $item) {
            // 仅保留需要的字段（id, title, spread, parent_id），过滤冗余字段
            $node = [
                'id' => $item['id'],
                'title' => $item['title'],
                'reference' => $item['number'],
                'spread' => $item['spread'] ? true :false,
              //  'children' => [] // 初始化子节点容器
            ];
            // 将节点存入索引数组（key为id，方便后续查找）
            $idIndex[$item['id']] = $node;
            // 3. 同时判断当前节点是否为顶级节点（parent_id为NULL或无效值）
            $parentId = $item['parent_id'];
            if (is_null($parentId) || !isset($idIndex[$parentId])) {
                // 顶级节点直接加入结果数组
                $treeResult[] = &$idIndex[$item['id']];
            } else {
                // 非顶级节点：加入父节点的children数组（通过引用直接操作，避免二次查找）
                $idIndex[$parentId]['children'][] = &$idIndex[$item['id']];
            }
            // 释放引用，避免内存泄漏
            unset($node);
        }
        // 4. 解除所有引用（确保返回的数组无循环引用问题）
        unset($idIndex);
        return $treeResult;
    }
    /**
     * @Notes:获取案卷数据
     * @author: Liao Hong
     * @Time: 2025/10/25   9:09
     * @Interface getList
     */
    public function getArchivesAdminList($params)
    {
        if(!isset($params['project_id']) || empty($params['project_id'])){
            throw new Exception('请传入项目id，项目id不能为空！');
        }
        $where[] = ['project_id','=',$params['project_id']];
        if(isset($params['name']) && !empty($params['name'])){
            $where[] = ['name','like','%'.$params['name'].'%'];
        }
        if(isset($params['reference']) || !empty($params['reference'])){
            $where[] = ['reference','=',$params['reference']];
            $limit = isset($parmas['limit']) ? $parmas['limit'] : 10;
            $row = ArchivesAdmin::query()->where($where)->paginate($limit);
            $row = !empty($row) ? $row->toArray() :[];
            return $row;
        }else{
            return [];
        }
    }

    /**
     * @Notes:获取卷内数据
     * @param $params
     * @return array
     * @throws Exception
     * @author: Liao Hong
     * @Time: 2025/10/25   11:01
     * @Interface getArchivesFileList
     */
    public function getArchivesFileList($params)
    {
        if(!isset($params['archives_id']) || empty($params['archives_id'])){
            throw new Exception('请传入案卷ID，案卷ID不能为空！');
        }
        $limit = isset($parmas['limit']) ? $parmas['limit'] : 10;
        $where[] = ['archives_id','=',intval($params['archives_id'])];
        if(isset($params['name']) && !empty($params['name'])){
            $where[] = ['name','like','%'.$params['name'].'%'];
        }
        if(isset($params['duty']) && !empty($params['duty'])){
            $where[] = ['duty','like','%'.$params['duty'].'%'];
        }
        $row = ArchivesFile::query()->where($where)->paginate($limit);
        $row = !empty($row) ? $row->toArray() :[];
        return $row;
    }

    /**
     * @Notes:推送借阅
     * @param $params
     * @author: Liao Hong
     * @Time: 2025/10/27   10:16
     * @Interface pullBorrow
     */
    public function pullBorrow($params)
    {
       if(!isset($params['type']) || empty($params['type'])){
           throw new Exception('类型必传，类型不能为空！');
       }
       if(!isset($params['borrow_type']) || empty($params['borrow_type'])){
           throw new Exception('借阅类型必传，类型不能为空！');
       }
       if(!isset($params['data_id']) || empty($params['data_id'])){
           throw new Exception('数据ID必传，数据ID不能为空！');
       }
       if(!isset($params['title']) || empty($params['title'])){
           throw new Exception('案卷名称必传，案卷名称不能为空！');
       }
       if(!isset($params['user_name']) || empty($params['user_name'])){
           throw new Exception('借阅人名称必传，借阅人名称不能为空！');
       }
       $params['created_at']       = getTime();
       $params['create_user_id']   = user_id();
       $params['create_user_name'] = user()->user_name;
       $reference = '';
       if($params['borrow_type'] == 1){
           //案卷
           $reference = ArchivesAdmin::query()->where('id',$params['data_id'])->value('reference');
       }elseif ($params['borrow_type'] == 2){
           //卷内
           $archivesId = ArchivesFile::query()->where('id',$params['data_id'])->value('archives_id');
           $reference  = ArchivesAdmin::query()->where('id',$archivesId)->value('reference');
       }
       $params['reference'] = $reference;
       $row = Borrow::query()->insertGetId($params);

       return $row;
    }

    /**
     * @Notes:借阅记录
     * @param $params
     * @author: Liao Hong
     * @Time: 2025/10/28   13:59
     * @Interface borrowList
     */
    public function borrowList($params)
    {
        $where = [];
        if(isset($params['user_name']) && !empty($params['user_name'])){
            $where[] = ['user_name','like','%'.$params['user_name'].'%'];
        }
        if(isset($params['title']) && !empty($params['title'])){
            $where[] = ['title','like','%'.$params['title'].'%'];
        }
        if(isset($params['type']) && !empty($params['type'])){
            $where[] = ['type','=',$params['type']];
        }
        $row = Borrow::query()->where($where)->get();
        $row = !empty($row) ? $row->toArray() :[];
        return $row;
    }

}
